package ar.fi.uba.fallas2.business;

import ar.fi.uba.fallas2.data.*;

abstract public class BusinessObject {
	private int id;
	private String entityName;
	
	public BusinessObject(String entityName) {
		this.setEntityName(entityName);
		this.setId(-1);
	}
	
	public BusinessObject(String entityName, int id) {
		this(entityName);
		this.setId(id);
	}
	
	protected boolean isNewEntity() {
		return this.getId() == -1;
	}

	protected void setId(int id) {
		this.id = id;
	}

	protected int getId() {
		return id;
	}

	protected void setEntityName(String entityName) {
		this.entityName = entityName;
	}

	protected String getEntityName() {
		return entityName;
	}
	
	public void save() throws DataException {
		if (this.isNewEntity()) {
			this.insert();
			this.setId(this.getInsertedId());
		} else {
			this.update();
		}
	}
	
	private int getInsertedId() {
		try {
			return GenericFinder.findLastObjectId();
		} catch (DataException ex) {
			ex.printStackTrace();
			return -1;
		}
	}
	
	public abstract void delete() throws DataException;
	
	protected abstract void insert() throws DataException;
	protected abstract void update() throws DataException;
}
